package com.i.template.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.i.template.constant.RedisConstants;
import com.i.template.constant.ResponseResult;
import com.i.template.domain.MemberFeeDO;
import com.i.template.domain.vo.MemberFeeVO;
import com.i.template.service.IMemberFeeService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @author lewis
 * @type class
 * @description
 * @since 2024/8/8
 */
@RestController
@RequestMapping("/fee")
@RequiredArgsConstructor
public class MemberFeeController {
    private final IMemberFeeService service;
    private final StringRedisTemplate stringRedisTemplate;

//    private final ObjectMapper objectMapper = new ObjectMapper();
    @GetMapping
    public ResponseResult<MemberFeeVO> queryFeeById(@RequestParam(required = false,value = "1") Integer id) throws JsonProcessingException {
        String str = stringRedisTemplate.opsForValue().get(RedisConstants.MEMBER_FEE_KEY);
        if(StringUtils.isNotBlank(str)) {
//            MemberFeeVO memberFeeVO = objectMapper.readValue(str, MemberFeeVO.class);
//            return ResponseResult.ok(memberFeeVO);
            return ResponseResult.ok(JSONUtil.toBean(str,MemberFeeVO.class));
        }
        MemberFeeVO memberFeeVO = BeanUtil.copyProperties(service.getById(id), MemberFeeVO.class);

        stringRedisTemplate.opsForValue().set(RedisConstants.MEMBER_FEE_KEY, JSONUtil.toJsonStr(memberFeeVO));
        return ResponseResult.ok(memberFeeVO);
    }
    @PutMapping
    public ResponseResult<Boolean> updateFollowById(@RequestBody MemberFeeVO memberFeeVO) {
        stringRedisTemplate.delete(RedisConstants.MEMBER_FEE_KEY);
        return ResponseResult.judge(service.updateById(BeanUtil.copyProperties(memberFeeVO, MemberFeeDO.class)));
    }
}
